// 云函数入口文件
const cloud = require('wx-server-sdk')
const md5 = require('md5-node')

cloud.init({
  traceUser: true,
  env: 'photo-duo0u'
})

const db = cloud.database()
const usersPassword = db.collection("password")

// 云函数入口函数
exports.main = async (event, context) => {
  const wxContext = cloud.getWXContext()
  //更新密码
  if (event.update == true) {
    try {
      return await usersPassword.doc(event.userData.userId).update({
        data: {
          userData: _.set(event.userData)
        },
      })
    } catch (e) {
      console.error("密码更新", e)
    }
  } else if (event.getSelf == true) {
    //获取当前用户密码
    try{
      let passwords = await db.collection('password').where({
        userId: event.userId
      }).get({
        user_password:true
      });
      passwords = passwords.data[0].user_password
      return passwords
    }catch(e){
      console.log("用户密码查询失败",e);
    }
    
  } else if (event.setSelf == true) {
    //添加当前用户密码
    try {
      console.log("event:",event);
      return await usersPassword.add({
        data: {
          userId: event.userData.userId,
          user_password: event.userData.user_password,
        }
      })
    } catch (e) {
      console.error("密码添加", e)
    }
  } else if (event.getOthers == true) {
    //获取指定用户信息
    try {
      return await usersPassword.doc(event.userId).field({
        userData: true
      }).get()
    } catch (e) {
      console.error("获取指定用户信息", e)
    }
  }
}